﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRepository;
using Infrastructures;
using Models;
using MongoDB.Driver;
using MongoDB.Bson;

namespace RepositoryMangoDB
{
    public class CommonRepository : ICommonRepository
    {
        internal CommonRepository() { }

        public virtual T Create<T>(T obj)
        {
            MongoCollection col = DBHelper.MangoDBInstance.GetCollection(obj.GetType().Name);
            col.Insert<T>(obj);

            return obj;
        }

        public virtual void Update<T>(T obj)
        {
            MethodHelper.ExecuteMethod(MethodType.Update, obj);
        }

        public virtual void Delete<T>(string code) 
        {
            MethodHelper.ExecuteMethod(MethodType.Delete, typeof(T), code);
        }

        public virtual List<T> List<T>() 
        {
            return (List<T>)MethodHelper.ExecuteMethod(MethodType.List, typeof(T));
        }

        public virtual T Get<T>(string code) 
        {
            MongoCollection<T> col = DBHelper.MangoDBInstance.GetCollection<T>(typeof(T).Name);
            return (T)(object)col.FindOneById(ObjectId.Parse(code));
        }


        public void Delete<T>(int code)
        {
            Delete<T>(code.ToString());
        }

        public T Get<T>(int code)
        {
            return Get<T>(code.ToString());
        }
    }
}
